import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers.common = {
      Authorization: 'Bearer ' + getToken()
    }

    // if (store.getters.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
    //   config.headers['X-Token'] = 'Bearer '+getToken()
    //   config.headers['Authorization'] ='Bearer '+getToken()
    //   console.log( config.headers['Authorization'])
    // }
    // console.log("config");
    // console.log(config)
    return config
  },
  error => {
    // do something with request error
    // console.log(error); // for debug
    return Promise.reject(error)
  }
)
export function downloadFile(url, params, fileName) {
  service
    .post(url, params, {
      responseType: 'blob' // 设置响应的数据类型为一个包含二进制数据的 Blob 对象，必须设置！！！
    })
    .then(res => {
      const linkNode = document.createElement('a')
      linkNode.download = fileName // a标签的download属性规定下载文件的名称
      linkNode.style.display = 'none'
      linkNode.href = URL.createObjectURL(res.data) // 生成一个Blob URL
      document.body.appendChild(linkNode)
      linkNode.click() // 模拟在按钮上的一次鼠标单击
      URL.revokeObjectURL(linkNode.href) // 释放URL 对象
      document.body.removeChild(linkNode)
    })
}

// export function fetchLoadFile(url, params, fileName) {
//   service
//     .get(url, params, {
//       responseType: "arraybuffer" // 设置响应的数据类型为一个包含二进制数据的 Blob 对象，必须设置！！！
//     })
//     .then(res => {
//      return res;
//     });
// }

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (res.code !== 20000) {
      Message({
        message: res.message || 'Error001',
        type: 'error',
        duration: 5 * 1000
      })
      if (res.code == 30002) {
        removeToken()
        // store.dispatch("user/logout");
        router.push('/login')
        return
      }

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm(
          'You have been logged out, you can cancel to stay on this page, or log in again',
          'Confirm logout',
          {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      if (res.code == 30002) {
        return
      }
      
      return Promise.reject(new Error(res.message || 'Error002'))
    } else {
      // Message({
      //   message: res.message || 'Error001',
      //   type: 'success',
      //   duration: 5 * 1000
      // })
      return res
    }
  },

  error => {
    if (error.message.substr(0, 7) == 'timeout') {
      error.message = '请求超时'
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
